'use strict';

const path = require('path');
const fs = require('fs');
// const out = require('./lib/out');
const yaml = require('js-yaml');

const cwd = process.cwd();
const token = process.env.YUQUE_TOKEN;
const defaultConfig = {
  postPath: 'source/_posts/yuque',
  cachePath: 'yuque.json',
  mdNameFormat: 'title',
  baseUrl: 'https://www.yuque.com/api/v2/',
  token,
  login: '',
  repo: '',
  adapter: 'hexo',
  concurrency: 5,
  onlyPublished: false,
  onlyPublic: false,
};

function loadConfig() {
  const cfg = loadYaml();
  const yuqueRepos = [];
  if (!cfg.repos && cfg.repo) {
    cfg.repos = [ cfg.repo ];
  }
  for (const repo of cfg.repos) {
    repo.baseUrl = cfg.baseUrl;
    repo.login = cfg.login;
    repo.mdNameFormat = cfg.mdNameFormat;
    repo.token = cfg.token;
    yuqueRepos.push(Object.assign({}, defaultConfig, repo));
  }
  return yuqueRepos;
}

function loadYaml() {
  try {
    return yaml.load(fs.readFileSync(path.join(cwd, '_config.yml'))).yuque;
  } catch (error) {
    // do nothing
  }
}

module.exports = loadConfig();
